<template>
  <scroller class="page">
    <div class="slider-container" v-if="imgs.length > 0">
      <slider class="slider" interval="5000" auto-play="true" @change="onImgIndexChanged">
        <div class="frame" v-for="img in imgs">
          <image class="image" resize="cover" :src="img"></image>
        </div>
      </slider>
      <div class="indicator">
        <text class="indicator-text">{{ imgIndex + 1 }} / {{ imgs.length }}</text>
      </div>
    </div>
    <image class="image" resize="cover" :src="info.cover" v-else></image>
    <div class="info-container">
      <div class="info">
        <div class="title">
          <text class="title-text">{{ info.title }}</text>
        </div>
        <div class="subtitle">
          <text class="subtitle-text">{{ info.subtitle }}</text>
        </div>
        <div class="price">
          <text class="price-text" v-if="info.minPrice">￥{{ info.minPrice }}-{{ info.maxPrice }}</text>
          <text class="price-text" v-else>￥{{ info.price }}</text>
        </div>
      </div>
      <div class="subscribe" @click="subscribe" v-if="!info.isSubscribed">
        <text>☆</text>
      </div>
      <div class="subscribe" @click="unsubscribe" v-else>
        <text>已收藏</text>
      </div>
    </div>
    <div class="services" v-if="services.length > 0">
      <div class="services-item" v-for="item in services">
        <text class="services-item-text">{{ item }}</text>
      </div>
    </div>
    <div class="content">
      <image class="gallery-image" resize="contain" :src="item" ref="gallery" v-for="(item, index) in gallery" @load="onImageLoad"></image>
      <!-- <text>© 2019 珠海蓁奕互联网科技有限公司</text> -->
    </div>
    <Footer />
    <div class="bottom">
      <div class="bottom-left">
        <div class="bottom-left-item" @click="goHome">
          <image class="bottom-left-item-img" resize="contain" src=""></image>
          <text class="bottom-left-item-text">首页</text>
        </div>
        <div class="bottom-left-item" @click="showModal(true)">
          <image class="bottom-left-item-img" resize="contain" src=""></image>
          <text class="bottom-left-item-text">购物车</text>
        </div>
      </div>
      <div class="bottom-right" @click="showModal(false)">
        <text class="bottom-right-text">立即购买</text>
      </div>
    </div>
    <div class="popup" v-if="modalVisible">
      <div class="popup-mask" @click="hideModal"></div>
      <div class="popup-box">
        <div class="popup-info">
          <image class="popup-img" resize="cover" :src="info.formats[selectedIndex].image" v-if="selectedIndex !== '' && info.formats[selectedIndex].image"></image>
          <image class="popup-img" resize="cover" :src="info.cover" v-else></image>
          <div class="popup-format">
            <text class="popup-format-price" v-if="!info.formats || info.formats.length <= 0">￥{{ info.price }}</text>
            <text class="popup-format-price" v-else-if="selectedIndex === ''">￥{{ info.minPrice }}-{{ info.maxPrice }}</text>
            <text class="popup-format-price" v-else>￥{{ info.formats[selectedIndex].fee }}</text>
            <text class="popup-format-title" v-if="info.formats && info.formats.length > 0 && selectedIndex !== ''">已选：{{ info.formats[selectedIndex].title }}</text>
          </div>
          <div class="popup-close" @click="hideModal">
            <text>X</text>
          </div>
        </div>
        <text class="popup-select-title" v-if="info.formats && info.formats.length > 0">规格选择</text>
        <div class="popup-select-list" v-if="info.formats && info.formats.length > 0">
          <div class="popup-select-item" :class="[selectedIndex === index ? 'popup-select-item-selected' : '']" v-for="(item, index) in info.formats" @click="selectFormat(item, index)">
            <text class="popup-select-text" :class="[selectedIndex === index ? 'popup-select-text-selected' : '']">{{ item.title }}</text>
          </div>
        </div>
        <!-- <text class="popup-select-title">配送时间</text>
        <div class="popup-select-list">
          <div class="popup-select-item" :class="[selectedTimeIndex === index ? 'popup-select-item-selected' : '']" v-for="(item, index) in times" @click="selectTime(item, index)">
            <text class="popup-select-text" :class="[selectedTimeIndex === index ? 'popup-select-text-selected' : '']">{{ item }}</text>
          </div>
        </div> -->
        <div class="popup-bottom" @click="goPay">
          <text class="popup-bottom-text">确定</text>
        </div>
      </div>
    </div>
  </scroller>
</template>
<script>
import Footer from '@/components/Footer';
import utils from './utils/utils.js';
const modal = weex.requireModule('modal');
const event = weex.requireModule('event');
const authChannel = new BroadcastChannel('auth');
export default {
  name: 'App',
  components: {
    Footer
  },
  data() {
    return {
      productId: '',
      info: {},
      imgs: [],
      imgIndex: 0,
      services: [],
      modalVisible: false,
      selectedIndex: '',
      times: ['当天下午15:00~17:00（当天16:00前下单选此项）', '次日上午09:00~12:00（当天16:00后下单选此项）', '自提'],
      selectedTimeIndex: '',
      gallery: [],
      isAddCart: false
    }
  },
  mounted() {
    event.initData(JSON.stringify({ 'title': '商品详情' }), json => {
      var data = JSON.parse(json);
      this.productId = data.productId;
      this.init();
    })

    // 收到成功登录信息时刷新页面
    authChannel.onmessage = event => {
      this.init();
    }
  },
  methods: {
    init() {
      var url = '/yq/product/info';
      var params = {
        productId: this.productId
      };
      var success = res => {
        console.log(res);
        this.info = res.info.product;

        if (this.info.images) {
          this.imgs = this.info.images.split(";");
          this.imgs.pop();
        }
        if (this.info.services) {
          this.services = this.info.services.split(";");
          this.services.pop();
        }
        if (this.info.gallery) {
          this.gallery = this.info.gallery.split(";");
          this.gallery.pop();
        }
      }
      var fail = res => {
        modal.toast({
          message: '获取数据失败',
          duration: 1
        })
      }
      utils.request(url, params, success, fail);
    },
    goPay() {
      if (!utils.checkToken()) {
        return;
      }
      var formatId = '';
      if (this.info.formats && this.info.formats.length > 0) {
        if (this.selectedIndex === '') {
          modal.toast({
            message: '请选择规格',
            duration: 2
          })
          return;
        }
        formatId = this.info.formats[this.selectedIndex].id;
      }
      if (this.isAddCart) {
        var url = '/yq/cart/update';
        var params = {
          productId: this.productId,
          formatId: formatId,
          count: 1
        };
        var success = res => {
          console.log(res);
          if (res.status == 200) {
            modal.toast({
              message: '加入购物车成功',
              duration: 2
            })
            this.hideModal();
          } else {
            modal.toast({
              message: '加入购物车失败',
              duration: 2
            })
          }
        }
        var fail = res => {
          modal.toast({
            message: '获取数据失败',
            duration: 1
          })
        }
        utils.request(url, params, success, fail);
      } else {
        var info = this.info;
        var format = this.info.formats[this.selectedIndex];
        info.formatId = format.id;
        info.formatImage = format.image;
        info.formatPrice = format.fee;
        info.formatTitle = format.title;
        info.count = 1;
        var listToPay = new Array;
        listToPay.push(info);

        var params = {
          path: 'confirm',
          data: JSON.stringify({
            list: listToPay,
            isFromCart: false
          })
        }
        event.onPush(JSON.stringify(params));
        this.hideModal();
      }
    },
    goHome() {
      event.onHome('', function () {});
    },
    subscribe() {
      if (!utils.checkToken()) {
        return;
      }
      var url = '/yq/user/subscribe';
      var params = {
        productId: this.productId
      };
      var success = res => {
        if (res.status == 200) {
          this.info.isSubscribed = 1;
          modal.toast({
            message: '收藏成功',
            duration: 1
          })
        } else {
          modal.toast({
            message: '收藏失败',
            duration: 1
          })
        }
      }
      var fail = res => {
        modal.toast({
          message: '收藏失败',
          duration: 1
        })
      }
      utils.request(url, params, success, fail);
    },
    unsubscribe() {
      if (!utils.checkToken()) {
        return;
      }
      var url = '/yq/user/unsubscribe';
      var params = {
        productId: this.productId
      };
      var success = res => {
        if (res.status == 200) {
          this.info.isSubscribed = 0;
          modal.toast({
            message: '取消收藏成功',
            duration: 1
          })
        } else {
          modal.toast({
            message: '取消收藏失败',
            duration: 1
          })
        }
      }
      var fail = res => {
        modal.toast({
          message: '取消收藏失败',
          duration: 1
        })
      }
      utils.request(url, params, success, fail);
    },
    showModal(isAddCart) {
      this.isAddCart = isAddCart;
      this.modalVisible = true;
    },
    hideModal() {
      this.modalVisible = false;
    },
    selectFormat(item, index) {
      this.selectedIndex = index;
    },
    selectTime(item, index) {
      this.selectedTimeIndex = index;
    },
    onImgIndexChanged(e) {
      this.imgIndex = e.index;
    },
    onImageLoad(event) {
      console.log(event);
      const view = event.target
      if (event.success) {
        if (WXEnvironment.platform === 'Web') {
          // view.style.width = event.size.naturalWidth + 'px';
          // view.style.height = event.size.naturalHeight + 'px';
          view.style.width = '690px';
          view.style.height = (event.size.naturalHeight) * (690 / event.size.naturalWidth) + 'px';
        } else {
          var animation = weex.requireModule('animation');
          animation.transition(view, {
            styles: {
              // width: event.size.naturalWidth + 'px',
              // height: event.size.naturalHeight + 'px'
              width: '690px',
              height: (event.size.naturalHeight) * (690 / event.size.naturalWidth) + 'px'
            },
            duration: 0, //需要设置为0，否则无效
            timingFunction: 'ease',
            delay: 0,
            needLayout: true, //变化后刷新界面
          }, function() {})
        }
      }
    }
  }
}
</script>
<style scoped>
text {
  font-size: 32px;
}

.page {
  padding-bottom: 150px;
}

.slider-container {
  position: relative;
}

.slider {
  width: 750px;
  height: 750px;
}

.frame {
  width: 750px;
  height: 750px;
  position: relative;
}

.image {
  width: 750px;
  height: 750px;
}

.indicator {
  position: absolute;
  bottom: 30px;
  right: 30px;
  padding: 10px 30px;
  background-color: rgba(0, 0, 0, 0.3);
  border-radius: 1000px;
}

.indicator-text {
  color: #fff;
  font-size: 28px;
}

.info-container {
  padding: 30px;
  flex-direction: row;
  justify-content: space-between;
}

.info {
  flex-direction: column;
}

.title {
  margin-bottom: 10px;
}

.title-text {
  font-weight: bold;
}

.subtitle {
  margin-bottom: 40px;
}

.subtitle-text {
  font-size: 28px;
  color: #888;
}

.price-text {
  color: #527a5f;
  font-size: 45px;
}

.services {
  padding: 30px;
  background-color: #efefef;
  flex-direction: row;
  flex-wrap: wrap;
}

.services-item {
  margin-right: 60px;
}

.services-item-text {
  font-size: 28px;
  color: #666;
}

.content {
  padding: 30px;
}

.gallery-image {
  width: 690px;
  height: 690px;
}

.bottom {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  border-top-width: 1px;
  border-top-style: solid;
  border-top-color: #aaa;
  flex-direction: row;
  justify-content: space-between;
  align-items: stretch;
  height: 110px;
}

.bottom-left {
  width: 250px;
  flex-direction: row;
  align-items: center;
}

.bottom-left-item {
  flex-direction: column;
  align-items: center;
  width: 125px;
  border-left-width: 1px;
  border-left-style: solid;
  border-left-color: #aaa;
}

.bottom-left-item-img {
  width: 60px;
  height: 60px;
  margin-bottom: 10px;
}

.bottom-left-item-text {
  font-size: 20px;
}

.bottom-right {
  width: 500px;
  justify-content: center;
  align-items: center;
  text-align: center;
  background-color: #527a5f;
}

.bottom-right-text {
  font-size: 34px;
  color: #fff;
}

.popup {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.popup-mask {
  background-color: rgba(0, 0, 0, 0.4);
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}

.popup-box {
  position: absolute;
  top: 200px;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
}

.popup-info {
  flex-direction: row;
  padding: 0 30px;
}

.popup-img {
  width: 200px;
  height: 200px;
  transform: translateY(-30px);
}

.popup-format {
  padding: 30px;
  width: 440px;
}

.popup-format-price {
  font-size: 44px;
  font-weight: bold;
}

.popup-format-title {
  color: #888;
  font-size: 28px;
}

.popup-close {
  padding-top: 30px;
  width: 50px;
}

.popup-select-title {
  padding-left: 30px;
  font-weight: bold;
}

.popup-select-list {
  flex-direction: row;
  flex-wrap: wrap;
  padding: 30px 30px 30px 50px;
}

.popup-select-item {
  background-color: #f5f5f5;
  padding: 10px 30px;
  margin-right: 30px;
  margin-bottom: 30px;
}

.popup-select-item-selected {
  background-color: #595758;
}

.popup-select-text {
  font-size: 24px;
  color: #595758;
}

.popup-select-text-selected {
  color: #fff;
}

.popup-bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 110px;
  background-color: #527a5f;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.popup-bottom-text {
  color: #fff;
}
</style>